﻿using System.Net;
using System.Web.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;

namespace Marbles.Core.Content.UrlShorten
{
    public class GoogleURLShortener : IUrlShortener
    {
        public string Shorten(string LongUrl)
        {
            string url = string.Empty;
            try
            {
                HttpWebRequest req = GetService();
                StreamWriter sw = new StreamWriter(req.GetRequestStream());
                sw.Write("{\"longUrl\": \"" + LongUrl + "\"}");
                sw.Close();
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string value = sr.ReadToEnd();
                sr.Close();
                resp.Close();

                if (resp.ContentType.Contains("application/json"))
                {
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    Dictionary<String, object> tmp = ser.DeserializeObject(value) as Dictionary<String, object>;
                    if (tmp.ContainsKey("id")) { url = tmp["id"].ToString(); }
                }
            }
            catch
            {
                url = string.Empty;
            }

            return url;
        }


        private HttpWebRequest GetService()
        {
            string url = string.Format("https://www.googleapis.com/urlshortener/v1/url?key={0}", Marbles.Resources.ResourceHandler.GetGoogleAPIKey());
            HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
            req.Proxy = HttpWebRequest.GetSystemWebProxy();
            req.Method = "POST";
            req.ContentType = "application/json";
            return req;
        }

    }
}
